package cn.bugio.note.auth;

import cn.bugio.note.util.JwtOperator;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


/**
 * @author Vincent Vic
 * @version 1.0
 * @Description aop
 * @since 2021/3/4
 */

@Aspect
@Component
@Slf4j
public class CheckLoginAspect {

    @Autowired
    private JwtOperator jwtOperator;

    /**
     * 处理加CheckLogin方法
     * @param point
     * @return
     */
    @Around("@annotation(cn.bugio.note.auth.CheckLogin)")
    public Object checkLogin(ProceedingJoinPoint point) {
        try {
            //1.从header里面获取token
            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
            ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes;
            HttpServletRequest request = attributes.getRequest();

            String token = request.getHeader("x-token");

            //2.校验token是否合法，不合法，直接抛异常；合法直接放行
            Boolean isValid = jwtOperator.validateToken(token);
            if (!isValid) {
                log.error("Token不合法！");
                throw new SecurityException("Token不合法！");
            }

            //3.校验成功，将用户信息设置到request的attribute里面
            Claims claims = jwtOperator.getClaimsFromToken(token);

            request.setAttribute("id",claims.get("id"));
            request.setAttribute("wxNickname",claims.get("wxNickname"));
            request.setAttribute("roles",claims.get("roles"));
            log.info("用户数据 : {}",claims);

            return point.proceed();
        } catch (Throwable throwable) {
            throw new SecurityException("Token不合法！");
        }
    }
}
